import Taro from "@tarojs/taro";
import { SubscribeMessageAction, TrackAction, WxTemplate } from '../../types/utils/subscribeMessage'


//订阅消息
export class SubscribeMessage {
  private static instance: SubscribeMessage;
  private templateList: WxTemplate[] = [];
  private isTaped: boolean;
  private track: TrackAction
  //实例化
  public static getInstance(): SubscribeMessage {
    if (this.instance == null) {
      this.instance = new SubscribeMessage();
    }
    return SubscribeMessage.instance;
  }
  //注册模板埋点事件
  public registTrack(res: TrackAction) {
    this.track = res;
  }
  //注册模板数据
  public registTemplateList(res: WxTemplate[]) {
    this.templateList = Array.from(new Set([...this.templateList, ...res]));
  }

  /**
   * 获取动作对应的模板id
   * @param action 动作
   */
  private tempsOf(action: SubscribeMessageAction) {
    return this.templateList
      .filter(res => {
        return (
          res &&
          action.indexOf(
            res.title || ""
          ) != -1
        );
      })
      .map(item => item.priTmplId || "");
  }

  private async check(p: {
    action: SubscribeMessageAction;
    result?: (res: boolean) => void;
  }) {
    let temps = this.tempsOf(p.action);
    if (!temps.length) {
      p.result && p.result(false);
      this.isTaped = false;
      return false;
    }
    if (this.isTaped) return false;
    this.isTaped = true;
    try {
      const res = await Taro.requestSubscribeMessage({
        tmplIds: temps
      });
      this.track && this.track('MessageSubscribe')
      if (res[temps[0]] === 'reject') {
        this.track && this.track('MessageSubscribe_cancel')
      } else {
        this.track && this.track('MessageSubscribe_success')
      }
      p.result && p.result(true);
      this.isTaped = false;
      return true;
    } catch (e) {
      p.result && p.result(false);
      this.isTaped = false;
      return false;
    }
  }

  /**
   * 检查并执行订阅
   * @param action 动作
   * @param result 结果回调
   */
  public static check(p: {
    action: SubscribeMessageAction;
    result?: (res: boolean) => void;
  }) {
    return SubscribeMessage.getInstance().check(p);
  }
}
